<template>
  <n-card :bordered="false" class="proCard">
    <BasicForm @register="register" @reset="handleReset" @submit="handleSubmit">
      <template #dateSelect="{ model, field }">
        <n-date-picker
          v-model:formatted-value="model[field]"
          clearable
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </template>
    </BasicForm>

    <BasicTable
      ref="actionRef"
      :columns="columns"
      :pagination="false"
      :request="loadDataTable"
      :scroll-x="2048"
    >
      <template #toolbar>
        <n-button type="warning" @click="downloadExcel">导出账单</n-button>
      </template>
    </BasicTable>
  </n-card>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref, unref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { columns } from './columns';
  import { useRouter } from 'vue-router';
  import { getStatisticsGameArea } from '@/api/statistics/daily';
  import { formatToDate } from '@/utils/dateUtil';
  import * as XLSX from 'xlsx';

  const schemas: FormSchema[] = [
    {
      field: 'timeRange',
      label: '日期',
      componentProps: {
        placeholder: '日期',
      },
      slot: 'dateSelect',
    },
  ];
  const router = useRouter();
  const formRef: any = ref(null);
  const message = useMessage();
  const dialog = useDialog();
  const actionRef = ref();
  let dataSource;
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formParams = reactive({
    timeRange: [],
  });

  const params = ref({});

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  const loadDataTable = async (res) => {
    const param = { ...formParams, ...res };
    console.log(param);
    const data = await getStatisticsGameArea(param);
    // console.log('data');
    // console.log(data);
    dataSource = data.list;
    return data;
  };

  function reloadTable() {
    actionRef.value.reload();
  }

  function handleSubmit(values: Recordable) {
    console.log('submit', values);
    let tempParams = unref(formParams);
    tempParams = Object.assign(tempParams, values);
    if (values.makeDate) {
      let [startTime, endTime]: [number, number] = values.makeDate;
      let startTimeS = formatToDate(new Date(startTime));
      let endTimeS = formatToDate(new Date(endTime));
      tempParams = Object.assign(tempParams, { startTime: startTimeS, endTime: endTimeS });
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  let json_fields = {
    areaName: '区服',
    roleNum: '角色数',
    totalRecharge: '累计充值',
    ltv: 'LTV',
  };
  const downloadExcel = () => {
    console.log(dataSource);
    // 创建工作表
    let list = unref(dataSource).map((item) => {
      const obj = {};
      for (const k in item) {
        if (json_fields[k]) {
          obj[json_fields[k]] = item[k];
        }
      }
      return obj;
    });
    const data = XLSX.utils.json_to_sheet(list);
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    // 每列不同宽度px
    let wscols = [
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 10 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
      { wch: 12 },
    ];
    data['!cols'] = wscols;
    // 将工作表放入工作簿中
    XLSX.utils.book_append_sheet(wb, data, 'data');
    // 生成文件并下载
    var date = new Date(Date.now());
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    var strDate = Y + M + D;
    XLSX.writeFile(wb, `悠游电竞游戏区服统计数据(${strDate}).xlsx`);
  };

  onMounted(async () => {
    // registerHandler(ItemTableSwitchActions);
    // const chanList = await getChanList();
    // registChanArray.value = chanList.map((chan) => {
    //   return {
    //     label: chan.chanName,
    //     value: chan.chanId
    //   }
    // });
  });
</script>

<style lang="less" scoped></style>
